/**
 * Copyright(c) KuGou-Inc.All Rights Reserved. 
 */
package top.suven.base.http.Interceptor;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import top.suven.base.http.enums.SysMsgEnumType;
import top.suven.base.http.exception.SystemRuntimeException;
import top.suven.base.http.message.ParamMessage;
import top.suven.base.http.message.RequestMessage;
import top.suven.base.http.message.RequestRemote;
import top.suven.base.http.processor.url.UrlExplain;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * <pre>
 * 程序的中文名称。
 * </pre>
 * @author andrewyang  yangjianjun@kugou.net
 * @version 1.00.00
 * <pre>
 * 修改记录
 *    修改后版本:     修改人：  修改日期:     修改内容: 
 * </pre>
 */
@Component
public class TokenHandlerInterceptor extends HandlerInterceptorAdapter {
	private Logger logger = LoggerFactory.getLogger(TokenHandlerInterceptor.class);

	@Autowired
	private UserTokenValidator userTokenValidator;



	public TokenHandlerInterceptor(ApplicationContext applicationContext){
        userTokenValidator = applicationContext.getBean("userTokenValidator", UserTokenValidator.class);
    }

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws SystemRuntimeException {
        RequestRemote remote = ParamMessage.getRequestRemote();
        RequestMessage message = ParamMessage.getRequestMessage();
        //验证服务是否维护
        boolean isMaintain = userTokenValidator.getProjectCache().getUnchecked(remote.getModule());
        if(isMaintain){
            userTokenValidator.getProjectCache().invalidate(remote.getModule());
            //系统维护中
            throw new SystemRuntimeException(SysMsgEnumType.SYS_PROJECT_MAINTAIN);
        }
        if(remote == null){
            logger.warn(" TokenHandlerInterceptor RequestRemote is null remote: [{}] ", remote );
            return true;
        }
        //get请求，不需要登陆
        if(!remote.isPostReq()){
            return true;
        }
        //url在白明单中，不需要验证
        if(UrlExplain.isWhite(remote.getUrl())){
            return true;
        }

        boolean isLogin = false;
        if(UrlExplain.mustCheck(remote.getUrl())){
            isLogin = userTokenValidator.passportVerify();
        }else {
            isLogin = userTokenValidator.getCache().getUnchecked(message.getUserId());
        }
        if(!isLogin){
            userTokenValidator.getCache().invalidate(message.getUserId());
            throw new SystemRuntimeException(SysMsgEnumType.SYS_TOKEN_NULL);
        }
		return true;

	}



}
